package com.czk.protocol.dubbo;


import com.czk.framework.Invocation;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

import java.util.concurrent.Callable;

/**
 * netty客户端处理器
 */
public class NettyClientHandler extends ChannelInboundHandlerAdapter implements Callable {
    /**
     * 拿到上下文
     */
    private ChannelHandlerContext context;
    /**
     * 定义全局协议封装体
     */
    private Invocation invocation;
    // 定义全局变量，节后返回结果
    private String result;

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        context = ctx;
    }

    @Override
    public synchronized void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        result = msg.toString();
        // 唤醒阅读线程
        notify();
    }

    public synchronized Object call() throws Exception {
        context.writeAndFlush(this.invocation);
        // 阻塞发送线程
        wait();
        return result;
    }

    public void setInvocation(Invocation invocation) {
        this.invocation = invocation;
    }
}
